package com.ohos.connect.devicecloud.app.modular.projectdevice.api;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ohos.connect.devicecloud.app.api.ProjectDeviceApi;
import com.ohos.connect.devicecloud.app.modular.projectdevice.model.entity.ProjectDevice;
import com.ohos.connect.devicecloud.app.modular.projectdevice.service.ProjectDeviceService;
import com.ohos.connect.devicecloud.app.modular.projectuser.service.ProjectUserService;
import com.ohos.connect.devicecloud.app.modular.user.model.entity.AppUser;
import com.ohos.connect.devicecloud.app.modular.user.service.AppUserService;
import com.ohos.connect.devicecloud.common.exception.CommonException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("projectDeviceApi")
public class ProjectDeviceApiImpl implements ProjectDeviceApi {

    @Resource
    private ProjectDeviceService projectDeviceService;

    @Resource
    private ProjectUserService projectUserService;

    @Resource
    private AppUserService appUserService;

    @Override
    public Boolean deleteProjectDevice(String deviceId) {
        return projectDeviceService.deleteProjectDevice(deviceId);
    }

    @Override
    public Boolean insertProjectDevice(String projectId, String deviceId) {
        ProjectDevice projectDevice = new ProjectDevice();
        projectDevice.setProjectId(projectId);
        projectDevice.setDeviceId(deviceId);

        return projectDeviceService.save(projectDevice);
    }

    @Override
    public String getUserAccountByDeviceId(String deviceId) {
        if (deviceId == null || deviceId.isEmpty()) {
            throw new CommonException("设备id不能为空");
        }

        String projectId = projectDeviceService.getProjectIdByDeviceId(deviceId);

        if (projectId == null || projectId.isEmpty() ) {
            throw new CommonException("当前设备没有归属项目");
        }

        String userId = projectUserService.getUserIdByProjectId(projectId);
        if (userId != null && ObjectUtils.isNotNull(userId)) {
            AppUser appUser = appUserService.getById(userId);
            if (appUser != null) {
                return appUser.getAccount();
            }
        }
        return "";
    }


}
